<template>
    <el-container class="outer">

        <el-aside class="aside" :class="{ collapsed: isCollapse }">
            <el-menu active-text-color="#ffd04b" background-color="#545c64" class="el-menu-vertical-demo custom-menu"
                default-active="2" text-color="#fff" :router="true">
                <template v-for="menu in menus" :key="menu.title">
                    <el-sub-menu v-if="Array.isArray(menu.children)" :index="menu.title">
                        <template #title>
                            <component class="icons" :is="icons[menu.icon]"
                                style="width: 1em; height: 1em; margin-right: 8px"></component>
                            <span>{{ menu.title }}</span>
                        </template>
                        <el-menu-item v-for="item in menu.children" :key="item.title" :index="item.url"
                            class="custom-menu-item">
                            <span>{{ item.title }}</span>
                        </el-menu-item>
                    </el-sub-menu>
                </template>
            </el-menu>
        </el-aside>
        <el-container>
            <el-header class="header">
                <div class="header-content">
                    <el-icon @click="toggleCollapse" class="toggle-icon">
                        <Expand v-if="isCollapse" />
                        <Fold v-else />
                    </el-icon>

                    <el-breadcrumb separator="/" class="breadcrumb">
                        <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
                        <el-breadcrumb-item v-for="(breadcrumb, index) in breadcrumbs" :key="index">
                            <a :href="breadcrumb.url">{{ breadcrumb.title }}</a>
                        </el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
                <div class="session">
                <el-menu background-color="#f3f8fe" @select="adminSelect">
                    <el-sub-menu index="admin">
                        <template #title>
                            <el-icon>
                                <Tools />
                            </el-icon>
                            {{ admin.username }}
                        </template>
                        <el-menu-item @click="editPassword">修改密码</el-menu-item>
                        <el-menu-item index="logout">退出</el-menu-item>
                    </el-sub-menu>
                </el-menu>
            </div>
            </el-header>
            <el-main class="main">
                <router-view v-slot="{ Component }">
                    <transition name="fade">
                        <keep-alive>
                            <component :is="Component" />
                        </keep-alive>
                    </transition>
                </router-view>
            </el-main>
        </el-container>
    </el-container>
    <div class="editPassword">
        <el-dialog v-model="show" title="修改密码" width="400" draggable>
            <el-form :model="editForm" ref="sfRef">
                <el-form-item label="原密码：" label-width="100px" prop="balance">
                    <el-input placeholder="请输入原密码" v-model="editForm.password" />
                </el-form-item>
                <el-form-item label="新密码：" label-width="100px" prop="balance">
                    <el-input placeholder="请输入新密码" v-model="editForm.newPassword" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="show = false">取消</el-button>
                    <el-button type="primary" @click="submitForm"> 确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup>
import { ref, computed,toRaw } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { User, Expand, Fold, ShoppingBag,House,View } from '@element-plus/icons-vue'
import { Tools } from '@element-plus/icons-vue'
import { clear as removeToken } from "@/api/JwtApi";
import { findByUsername, updateAdminPassword } from "@/api/AdminApi";
import { ElMessage } from 'element-plus';
import { onMounted } from 'vue';

const router = useRouter();
const route = useRoute();
const icons = { User, ShoppingBag,House,View };

const isCollapse = ref(false);
const menus = ref([
    {
        title: "首页",
        icon: "House",
        children:[
            {
                title:"数据展示",
                url:"/index/view",
            }
        ]
    },
    {
        title: "订单管理",
        icon: "ShoppingBag",
        children: [
            {
                title: "订单列表",
                url: "/index/order",
            },
        ]
    },
    {
        title: "商品信息",
        icon: "ShoppingBag",
        children: [
            {
                title: "商品列表",
                url: "/index/item",
            },
            {
                title: "品牌列表",
                url: "/index/brand",
            },
            {
                title: "类型列表",
                url: "/index/categories"
            }
        ]
    },
    {
        title: "系统管理",
        icon: "User",
        children: [
            {
                title: "管理员列表",
                url: "/index/admin",
            },
          {
            title: "用户组列表",
            url: "/index/adminGroup",
          },
          {
            title: "权限列表",
            url: "/index/perm",
          },
          {
            title: "资源列表",
            url: "/index/resource"
          },
            {
                title: "会员列表",
                url: "/index/member"
            },{
                title: "角色列表",
                url: "/index/role"
            }
        ]
    },
]);
function adminSelect(menu) {
    if (menu === "logout") {
        removeToken(); // 清除 token
        admin.value = {}; // 清空用户信息
        router.push("/login"); // 跳转登录页
    }
}
onMounted(() => {
    // getAdmin();
})
const admin = ref([]);
async function getAdmin() {
    let resp = await findByUsername();
    console.log(resp.data);
    if (resp.success) {
        admin.value = resp.data;
    }
}
const show = ref(false);
const editForm = ref({
    password: "",
    newPassword: ""
})
function editPassword() {
    show.value = true;
}
function submitForm() {
    let pas = toRaw(editForm.value);
    let password = {
        password: pas.password,
        newPassword: pas.newPassword
    };
    console.log(password); // 打印 password 对象，确保其值正确
    submitEdit(admin.value.id, password);
}
async function submitEdit(id, password) {
    console.log(id, password);
    let resp = await updateAdminPassword(id, password);
    if (resp.success) {
        ElMessage({
            message: resp.message,
            type: 'success',
        });
        show.value = false;
    } else {
        ElMessage({
            message: resp.error,
            type: 'error',
        });
    }
}
const breadcrumbs = computed(() => {
    const crumbs = [];
    const currentPath = route.path;
    let hasAddedParentMenu = false;  // 用于标记父菜单是否已经添加
    let isDetailPage = false; // 用于判断是否为详情页

    // 遍历菜单，找到当前路径对应的菜单项
    menus.value.forEach(menu => {
        menu.children.forEach(child => {
            if (currentPath === child.url) {
                crumbs.unshift({ title: child.title, url: child.url });
                hasAddedParentMenu = true; // 添加父菜单后设置标记为 true
            }

            // 如果路径包含 /index/order/，说明是在订单详情页面
            if (currentPath.includes('/index/order/') && currentPath !== '/index/order') {
                if (!isDetailPage) {
                    crumbs.unshift({ title: '订单详情', url: currentPath });
                    isDetailPage = true; // 避免重复添加订单详情
                }
            }
        });

        // 只添加一次父菜单项
        if (!hasAddedParentMenu && currentPath.startsWith(menu.children[0].url)) {
            crumbs.unshift({ title: menu.title, url: menu.children[0].url });
            hasAddedParentMenu = true;  // 添加父菜单后设置标记为 true
        }
    });

    return crumbs;
});


const toggleCollapse = () => {
    isCollapse.value = !isCollapse.value;
    console.log('Collapse state:', isCollapse.value);
};

</script>

<style scoped>
html,
body {
    height: 100%;
    margin: 0;
    padding: 0;
}

.outer {
    height: 100vh;
    display: flex;
    margin: 0;
    padding: 0;
}

.aside {
    height: 100%;
    width: 200px;
    margin: 0;
    padding: 0;
}

.el-menu-vertical-demo {
    height: 100%;
}

.header {
    background-color: #f3f8fe;
    border-bottom: 1px solid #ccc;
    display: flex;
    flex-direction: row;
    padding-left: 5px;
    height: 70px;
}

.header>.title {
    flex-grow: 1;
}

.header>.title>h1 {
    font-size: 24px;
    margin: 15px 0;
}

.header>.logo {
    width: 120px;
    flex-shrink: 0;
    box-sizing: border-box;
    padding: 5px;
    background: url("@/assets/111.png") no-repeat center center/contain;
    background-size: 120px;
}

.header > .session {
  width: 150px;
  flex-shrink: 0;
  margin-left: auto;  /* 关键：把它推到最右边 */
}
.header {
    z-index: 10;
}

.toggle-icon {
    cursor: pointer;
}

.breadcrumb {
    flex-grow: 1;
}

.main {
    height: calc(100% - 50px);
    background-color: #ffffff;
    overflow: auto;
    margin: 0;
    padding: 0;
}


.fade-enter-from {
    /* 进入时的透明度为0 和 刚开始进入时的原始位置通过active透明度渐渐变为1 */
    opacity: 0;
    transform: translateX(-100%);
}

.fade-enter-to {
    /*定义进入完成后的位置 和 透明度 */
    transform: translateX(0%);
    opacity: 1;
}

.fade-leave-active,
.fade-enter-active {
    transition: all 0.3s ease-out;
}

.fade-leave-from {
    /* 页面离开时一开始的css样式,离开后为leave-to，经过active渐渐透明 */
    transform: translateX(0%);
    opacity: 1;
}
.header>.session {
    width: 150px;
    flex-shrink: 0;
}
.fade-leave-to {
    /* 这个是离开后的透明度通过下面的active阶段渐渐变为0 */
    transform: translateX(100%);
    opacity: 0;
}
</style>
